import 'dart:convert';
import 'dart:io';

import 'package:enter_prise_web/common/constants.dart';
import 'package:enter_prise_web/routes/app_routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:get/get.dart';

class app extends StatefulWidget {
  const app({super.key});

  @override
  State<app> createState() => _appState();
}

class _appState extends State<app> {
  String _message = '';

  String _customJson = '';

  final _updateUrl =
      'https://gitee.com/lang-jun/enter_price_web/raw/master/assets/update_custom.json';

  @override
  void initState() {
    super.initState();


    initXUpdate();
    loadJsonFromAsset();

    checkUpdateDefault();
  }

  void initXUpdate() {
    if (Platform.isAndroid) {
      FlutterXUpdate.init(
              //是否输出日志
              debug: true,
              //是否使用post请求
              isPost: false,

              //post请求是否是上传json
              isPostJson: false,
              //请求响应超时时间
              timeout: 25000,
              //是否开启自动模式
              isWifiOnly: false,
              //是否开启自动模式
              isAutoMode: false,

              //需要设置的公共参数
              supportSilentInstall: false,
              retryUrl: _updateUrl,
              retryContent: "正在尝试重新下载...",
              //在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
              enableRetry: false)
          .then((value) {
        print("初始化成功: $value");
      }).catchError((error) {
        print("eee$error");
      });

      FlutterXUpdate.setErrorHandler(
          onUpdateError: (Map<String, dynamic>? message) async {
        print("sss$message");
      });

      FlutterXUpdate.setUpdateHandler(
          onUpdateError: (Map<String, dynamic>? message) async {
        print("ssddds$message");

        //下载失败
        if (message!["code"] == 4000) {
          FlutterXUpdate.showRetryUpdateTipDialog(
              retryContent: 'Github被墙无法继续下载，是否考虑切换蒲公英下载？',
              retryUrl: 'https://www.pgyer.com/flutter_learn');
        }
        setState(() {
          _message = '$message';
        });
      }, onUpdateParse: (String? json) async {
        //这里是自定义json解析

        return customParseJson(json!);
      });
    } else {
      debugPrint("ios暂不支持XUpdate更新");
    }
  }

  ///默认App更新
  void checkUpdateDefault() {
    FlutterXUpdate.checkUpdate(url: _updateUrl);
  }

  ///默认App更新 + 支持后台更新
  void checkUpdateSupportBackground() {
    FlutterXUpdate.checkUpdate(url: _updateUrl, supportBackgroundUpdate: true);
  }

  ///自动模式, 如果需要完全无人干预，自动更新，需要root权限【静默安装需要】
  void checkUpdateAutoMode() {
    FlutterXUpdate.checkUpdate(url: _updateUrl, isAutoMode: true);
  }

  void updateMessage(String message) {
    setState(() {
      _message = message;
    });
  }

  Future<void> loadJsonFromAsset() async {
    _customJson = await rootBundle.loadString('assets/update_custom.json');
  }

  ///将自定义的json内容解析为UpdateEntity实体类
  UpdateEntity customParseJson(String json) {
    print("json$json");
    AppInfo appInfo = AppInfo.fromJson(json);
    print(appInfo);
    return UpdateEntity(
        hasUpdate: appInfo.hasUpdate,
        isIgnorable: appInfo.isIgnorable,
        versionCode: appInfo.versionCode,
        versionName: appInfo.versionName,
        updateContent: appInfo.updateLog,
        downloadUrl: appInfo.apkUrl,
        apkSize: appInfo.apkSize);
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(
            backgroundColor: kDefaualtBgColor,
            elevation: 0,
            titleTextStyle: TextStyle(color: Colors.black, fontSize: 25),
            iconTheme: IconThemeData(
              color: Colors.black,
            )),
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
      debugShowCheckedModeBanner: false,
      defaultTransition: Transition.rightToLeft,
      getPages: AppPages.pages,
      initialRoute: Routes.splash,
    );
  }
}

class AppInfo {
  final bool? hasUpdate;

  final bool? isIgnorable;

  final String? apkUrl;

  final int? apkSize;

  final String? updateLog;

  final String? versionName;

  final int? versionCode;

  AppInfo(
      {this.hasUpdate,
      this.isIgnorable,
      this.apkUrl,
      this.apkSize,
      this.updateLog,
      this.versionName,
      this.versionCode});

  static AppInfo fromJson(String jsonStr) {
    final json = jsonDecode(jsonStr);
    return AppInfo(
      hasUpdate: json['hasUpdate'],
      isIgnorable: json['isIgnorable'],
      apkUrl: json['apkUrl'],
      apkSize: json['apkSize'],
      updateLog: json['updateLog'],
      versionName: json['versionName'],
      versionCode: json['versionCode'],
    );
  }
}
